package hot;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author way
 * @create 2025-03-04 20:11
 */
public class _42_trap {
    public int trap(int[] height) {
        int ans = 0;
        int n = height.length;
        int[] preMax = new int[height.length];
        int[] sufMax = new int[height.length];
        preMax[0] = height[0];
        for (int i = 1; i < n; i++) {
            preMax[i] = Math.max(preMax[i - 1], height[i]);
        }
        sufMax[n - 1] = height[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            sufMax[i] = Math.max(sufMax[i + 1], height[i]);
        }

        for (int i = 0; i < n; i++) {
            ans += Math.min(preMax[i], sufMax[i]) - height[i];
        }
        return ans;
    }

    public int trap_stack(int[] height) {
        int ans = 0;
        Deque<Integer> stack = new LinkedList<>();

        for (int i = 0; i < height.length; i++) {
            while (!stack.isEmpty() && height[i] >= height[stack.peek()]) {
                Integer bottom = stack.pop();
                if (stack.isEmpty()) break;

                int left = stack.peek();
                int h = Math.min(height[left], height[i]) - height[bottom];
                ans += h * (i - left - 1);
            }
            stack.push(i);
        }
        return ans;
    }
}
